package com.alcohol.auth.server.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author LiXinYu
 * @date 2025/11/11
 */
public class HttpServletUtils {

    /**
     * 获取 HttpServletRequest
     * @return {HttpServletRequest}
     */
    public static Optional<HttpServletRequest> getRequest() {
        return Optional.of(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest());
    }


    /**
     * 从HttpServletRequest中获取参数并转换为MultiValueMap
     * @param request HttpServletRequest对象
     * @return 包含所有参数的MultiValueMap，key为参数名，value为参数值列表
     */
    public static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
        parameterMap.forEach((key, values) -> {
            for (String value : values) {
                parameters.add(key, value);
            }
        });

        return parameters;
    }
}
